<template>
  <div class="permission-container">
    <div class="page-header">
      <h2>权限管理系统</h2>
    </div>
    
    <el-card class="main-card">
      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 人员角色分配 -->
        <el-tab-pane label="人员角色分配" name="userRole">
          <div class="user-role-section">
            <!-- 操作栏 -->
            <div class="operation-bar">
              <div class="search-box">
                <el-input
                  v-model="searchKeyword"
                  placeholder="请输入用户名或姓名搜索"
                  prefix-icon="el-icon-search"
                  clearable
                  @clear="handleSearch"
                  @keyup.enter.native="handleSearch"
                >
                </el-input>
                <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
              </div>
              <el-button type="success" icon="el-icon-plus" @click="showAddUserDialog">新增人员</el-button>
            </div>

            <!-- 用户列表 -->
            <el-table
              :data="users"
              style="width: 100%"
              border
              stripe
              highlight-current-row
            >
              <el-table-column prop="accountName" label="用户名" width="150" align="center">
              </el-table-column>
              <el-table-column prop="phone" label="手机号" width="150" align="center">
              </el-table-column>
              <el-table-column prop="lastLoginTime" label="最后登录时间" width="180" align="center">
                <template slot-scope="scope">
                  {{ scope.row.lastLoginTime ? scope.row.lastLoginTime.substring(0, 16).replace('T', ' ') : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="当前角色" width="150" align="center">
                <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.roleName ? 'success' : 'info'"
                    size="medium"
                    effect="plain"
                  >
                    {{ scope.row.roleName || '未分配' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-user"
                    @click="showAssignRoleDialog(scope.row)"
                  >分配角色</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              >
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>

        <!-- 角色权限配置 -->
        <el-tab-pane label="角色权限配置" name="roleResource">
          <div class="role-section">
            <div class="role-header">
              <el-button type="success" icon="el-icon-plus" @click="showAddRoleDialog">
                添加角色
              </el-button>
            </div>
            
            <el-table
              :data="allRoles"
              style="width: 100%"
              border
              stripe
              highlight-current-row
            >
              <el-table-column prop="roleName" label="角色名称" align="center">
              </el-table-column>
              <el-table-column label="操作" width="250" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-setting"
                    @click="handleConfigResource(scope.row)"
                  >配置权限</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    icon="el-icon-delete"
                    @click="handleDeleteRole(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增人员对话框 -->
    <el-dialog
      title="新增人员"
      :visible.sync="addUserDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="80px">
        <el-form-item label="用户名" prop="accountName">
          <el-input v-model="userForm.accountName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="assignRoleDialogVisible" width="30%">
      <el-radio-group v-model="selectedRole">
        <el-radio
          v-for="role in allRoles"
          :key="role.roleId"
          :label="role.roleId"
        >
          {{ role.roleName }}
        </el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAssignRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible">
      <el-form :rules="roleRules" ref="roleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 配置资源权限对话框 -->
    <el-dialog 
      title="配置资源权限" 
      :visible.sync="resourceDialogVisible"
      width="50%"
      @close="handleResourceDialogClose"
    >
      <el-tree
        ref="resourceTree"
        :data="resources"
        show-checkbox
        node-key="resourceId"
        :default-checked-keys="checkedResources"
        :props="{
          children: 'children',
          label: 'resourceName'
        }"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleResourceDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleSaveResource">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Permission',
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'userRole',
      
      // 用户管理相关数据
      searchKeyword: '',
      users: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 分配角色相关
      assignRoleDialogVisible: false,
      selectedRole: null,
      currentUser: null,
      allRoles: [
        // 模拟所有角色数据
        { roleId: 1, roleName: '暂无权限' },
      ],

      // 角色列表
      roles: [
        // 模拟数据
        { id: 1, roleName: '管理员', description: '系统管理员' },
        { id: 2, roleName: '普通用户', description: '普通用户权限' }
      ],
      
      // 资源树数据
      resources: [],
      
      // 树形控件配置
      defaultProps: {
        children: 'children',
        label: 'resourceName'
      },
      
      // 当前选中的角色ID
      currentRoleId: null,
      
      // 已选中的资源ID列表
      checkedResources: [],
      
      // 对话框显示控制
      addRoleDialogVisible: false,
      resourceDialogVisible: false,
      
      // 移除roleForm，只保留roleName
      roleName: '',
      
      // 表单验证规则
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      
      // 新增用户相关
      addUserDialogVisible: false,
      userForm: {
        accountName: '',
        phone: ''
      },
      userRules: {
        accountName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  
  methods: {
    // 搜索用户
    handleSearch() {
      this.$http.get('/platform/account/selectAccount',{
        params: {
          accountName: this.searchKeyword,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.users = res.data.data.list.reverse() // 对数据进行倒序处理
          this.total = res.data.data.total
        } else {
          this.$message.error('搜索失败')
        }
      })
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.handleSearch()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.handleSearch()
    },
    
    // 显示分配角色对话框
    showAssignRoleDialog(user) {
      this.currentUser = user
      this.selectedRole = user.roleId || null
      this.assignRoleDialogVisible = true
    },
    
    // 分配角色
    async handleAssignRole() {
      if (!this.selectedRole) {
        this.$message.warning('请选择要分配的角色')
        return
      }

      // TODO: 调用分配角色接口
      let form=new FormData()
      form.append('accountId', this.currentUser.accountId)
      form.append('roleId', this.selectedRole)
      this.$http.post('/platform/accountRole/addRole/',form).then(res => {
        if (res.data.code == 200) {
          this.$message.success('角色分配成功')
          this.assignRoleDialogVisible = false
          this.handleSearch() // 重新加载用户列表
        }else {
          this.$message.error('角色分配失败')
        }
      })
    },
    
    // 显示添加角色对话框
    showAddRoleDialog() {
      this.addRoleDialogVisible = true
    },
    
    // 添加角色
    async handleAddRole() {
        let form=new FormData()
        form.append('roleName', this.roleName)
        const res = await this.$http.post('/platform/role/addRole',form).then(res => {
          if (res.data.code === 200) {
            this.$message.success('添加成功')
            this.addRoleDialogVisible = false
            this.fetchRoles() // 重新获取角色列表
          } else {
            this.$message.error('添加失败')
          }
        })
    },
    
    // 删除角色
    async handleDeleteRole(role) {
      try {
        await this.$confirm('确认删除该角色?', '提示', {
          type: 'warning'
        })
        let form=new FormData()
        form.append('roleId',role.roleId)
        await this.$http.post('/platform/role/deleteRole',form)
        this.$message.success('删除成功')
        this.fetchRoles() // 重新获取角色列表
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    
    // 配置资源权限
    async handleConfigResource(role) {
      this.currentRoleId = role.roleId
      this.checkedResources = [] // 先清空选中状态
      this.resourceDialogVisible = true
      
      try {
        // 获取该角色的资源权限
        const res = await this.$http.get('/platform/resource/getRoleResource',{
              params: { roleId: role.roleId }
        })
        if (res.data.code === 200) {
          // 只设置后端返回的资源ID为选中状态
          this.checkedResources = res.data.data.map(item => item.resourceId)
          
          // 等待DOM更新后设置选中状态
          this.$nextTick(() => {
            if (this.$refs.resourceTree) {
              // 先清空所有选中状态
              this.$refs.resourceTree.setCheckedKeys([])
              // 只设置子节点的选中状态
              const leafNodes = this.checkedResources.filter(id => {
                const node = this.$refs.resourceTree.getNode(id)
                return node && (!node.childNodes || node.childNodes.length === 0)
              })
              this.$refs.resourceTree.setCheckedKeys(leafNodes)
            }
          })
        } else {
          this.$message.error('获取角色权限失败')
        }
      } catch (error) {
        this.$message.error('获取权限数据失败')
      }
    },
    
    // 修改保存资源权限配置方法
    async handleSaveResource() {
      // 获取所有选中的节点（包括父节点和子节点）
      const checkedKeys = this.$refs.resourceTree.getCheckedKeys()
      // 获取半选中的节点（父节点）
      const halfCheckedKeys = this.$refs.resourceTree.getHalfCheckedKeys()
      
      try {
        const res = await this.$http.post('/platform/resource/saveRoleResource', {
          roleId: this.currentRoleId,
          resourceIds: [...checkedKeys, ...halfCheckedKeys]
        })
        
        if (res.data.code === 200) {
          this.$message.success('保存成功')
          this.handleResourceDialogClose()
        } else {
          this.$message.error(res.data.message || '保存失败')
        }
      } catch (error) {
        this.$message.error('保存失败')
      }
    },
    
    // 修改对话框关闭处理方法
    handleResourceDialogClose() {
      this.resourceDialogVisible = false
      this.currentRoleId = null
      this.checkedResources = []
      if (this.$refs.resourceTree) {
        this.$refs.resourceTree.setCheckedKeys([])
      }
    },
    
    // 获取所有角色
    async fetchRoles() {
      // TODO: 实现获取角色列表的接口调用
      this.$http.get('/platform/role/selectAllRole').then(res => {
        if (res.data.code === 200) {
          this.allRoles = res.data.data
        } else {
          this.$message.error('获取角色列表失败')
        }
      })
    },
    
    // 获取所有资源
    async fetchResources() {
      try {
        const res = await this.$http.get('/platform/resource/getAllResource')
        if (res.data.code === 200) {
          this.resources = res.data.data
        } else {
          this.$message.error('获取资源列表失败')
        }
      } catch (error) {
        this.$message.error('获取资源列表失败')
      }
    },
    
    // 显示新增用户对话框
    showAddUserDialog() {
      this.addUserDialogVisible = true
      this.userForm = {
        accountName: '',
        phone: ''
      }
    },
    
    // 新增用户
    handleAddUser() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          try {
            const res = await this.$http.post('/platform/account/AddAccount', this.userForm)
            if (res.data.code === 200) {
              this.$message.success('添加成功')
              this.addUserDialogVisible = false
              this.handleSearch()
            } else {
              this.$message.error(res.data.message || '添加失败')
            }
          } catch (error) {
            this.$message.error('添加失败')
          }
        }
      })
    }
  },
  
  created() {
    this.handleSearch(),
        this.fetchRoles(),
        this.fetchResources()
  }
}
</script>

<style scoped>
.permission-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #303133;
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.main-card {
  background: #fff;
  border-radius: 4px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box .el-input {
  width: 300px;
}

.user-role-section,
.role-section {
  padding: 20px;
}

.role-header {
  margin-bottom: 20px;
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

/* 覆盖一些Element UI的默认样式 */
:deep(.el-table) {
  margin-top: 15px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

:deep(.el-tabs--border-card) {
  box-shadow: none;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}
</style> 